package com.ezhuan.outer.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ezhuan.common.controller.BaseController;
import com.ezhuan.common.util.ConstatFinalUtil;
import com.ezhuan.common.util.PageInfoUtil;
import com.ezhuan.system.service.ISystemService;
import com.ezhuan.system.service.impl.SystemServiceImplay;
import com.ezhuan.users.pojo.AIntegralHistory;
import com.ezhuan.users.pojo.AIntegralHistoryEnum;
import com.ezhuan.users.pojo.AUsers;
import com.ezhuan.users.pojo.AUsersWithdraw;
import com.ezhuan.users.pojo.AWithdrawHistory;
import com.ezhuan.users.service.IIntegralService;
import com.ezhuan.users.service.IUsersService;
import com.ezhuan.users.service.impl.IntegralServiceImpl;
import com.ezhuan.users.service.impl.UsersServiceImpl;

import sun.misc.BASE64Decoder;

/**
 * 和用户相关的Controller
 * 
 * @author wangshSxt
 *
 */
public class UsersOuterController extends BaseController
{
	/* 用户Service的实现类 */
	private IUsersService usersService = new UsersServiceImpl();
	private ISystemService systemService = new SystemServiceImplay();
	private IIntegralService integralService = new IntegralServiceImpl();

	/**
	 * 查看用户的详细信息
	 */
	public void usersInfo()
	{
		ConstatFinalUtil.LOGGER.info("======usersInfo======");
		long st = System.currentTimeMillis() ; 
		/* 存储结果的JSON */
		JSONObject resultJSON = new JSONObject();
		/* 接收参数 */
		String id = this.getPara("id");
		if (id == null)
		{
			id = "";
		}
		try
		{
			/* 查询数据库 */
			Map<String, Object> condMap = new HashMap<String, Object>();
			condMap.put("id", id);
			condMap.put("extend", "true");
			AUsers users = this.usersService.findOneUsersService(condMap);
			/* 查询结果 */
			if (users != null)
			{
				JSONObject dataJSON = users.toJSON();
				resultJSON.put("data", dataJSON);
				resultJSON.put("code", "0");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			} else
			{
				resultJSON.put("code", "1");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("1"));
			}
		} catch (Exception e)
		{
			ConstatFinalUtil.LOGGER.error("查询用户详细报错了:id:{}", id, e);
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-1") + e.toString());
		}
		long ed = System.currentTimeMillis() ;
		resultJSON.put("consumeTime", (ed - st) + "毫秒");
		/* 封装结果 */
		renderJson(resultJSON);
		System.out.println(resultJSON);
	}

	/**
	 * 查看用户的详细信息
	 */
	public void usersList()
	{
		ConstatFinalUtil.LOGGER.info("======usersList======");
		long st = System.currentTimeMillis() ;
		/* 存储结果的JSON */
		JSONObject resultJSON = new JSONObject();
		/* 接收参数 */
		String parentId = this.getPara("parentId");
		String secParentId = this.getPara("secParentId");
		String photoPath = this.getPara("photoPath");
		String orderby = this.getPara("orderby");
		
		try
		{
			PageInfoUtil pageInfoUtil = this.proccedPageInfoUtil();
			/* 查询数据库 */
			Map<String, Object> condMap = new HashMap<String, Object>();
			condMap.put("parentId", parentId);
			condMap.put("secParentId", secParentId);
			condMap.put("orderby", orderby);
			condMap.put("photoPath", photoPath);
			condMap.put("extend", "true");
			List<AUsers> usersList = this.usersService.findCondListUsersService(pageInfoUtil, condMap);
			if (usersList != null)
			{
				/* 数据 */
				JSONObject dataJSON = new JSONObject();
				// json数组 
				JSONArray usersArr = new JSONArray();
				for (Iterator iterator = usersList.iterator(); iterator.hasNext();)
				{
					AUsers users = (AUsers) iterator.next();
					JSONObject usersJSON = users.toJSON();
					usersArr.add(usersJSON);
				}
				dataJSON.put("usersList", usersArr);

				/* 存储分页相关的信息 */
				dataJSON.put("pageInfo", pageInfoUtil.toJSON());

				resultJSON.put("data", dataJSON);
				resultJSON.put("code", "0");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			} else
			{
				resultJSON.put("code", "1");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("1"));
			}
		} catch (Exception e)
		{
			ConstatFinalUtil.LOGGER.error("查询用户详细报错了:id:{}", parentId, e);
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-1") + e.toString());
		}
		long ed = System.currentTimeMillis() ;
		resultJSON.put("consumeTime", (ed - st) + "毫秒");
		/* 封装结果 */
		renderJson(resultJSON);
		System.out.println(resultJSON);
	}
	
	/**
	 * 用户更新
	 * 情况区分 
	 * 
	 * @return
	 */
	public void usersUpdateSubmit()
	{
		ConstatFinalUtil.LOGGER.info("======usersUpdateSubmit======");
		long st = System.currentTimeMillis() ;
		JSONObject resultJSON = new JSONObject();
		
		/* 接收参数 */
		String operType = this.getPara("operType");
		String uid = this.getPara("uid");
		
		try
		{
			/* 先查询用户 */
			Map<String, Object> condMap = new HashMap<String, Object>();
			condMap.put("id", uid);
			AUsers users = this.usersService.findOneUsersService(condMap);
			
			boolean upflag = false; 
			if("updatePass".equalsIgnoreCase(operType))
			{
				/* 更新密码 */
				String souPass = this.getPara("souPass");
				String password = this.getPara("password");
				if(this.encryptUtil.checkPass(souPass, users.getPassword()))
				{
					/* 更新密码 */
					users.setPassword(this.encryptUtil.encodePass(password));
					upflag = true ; 
				}else
				{
					/* 原密码不正确 */
					resultJSON.put("code", "4");
					resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("4"));
				}
			}else if("updatePerInfo".equalsIgnoreCase(operType))
			{
				/* 更新个人信息 */
		//		String regionId = this.getPara("regionId");
		//		String email = this.getPara("email");
				String nickName = this.getPara("nickName");
				
				/* 设置用户信息 */
		//		users.setEmail(email);
				users.setNickName(nickName);
		//		users.setRegionId(Integer.valueOf(regionId));
				upflag = true ; 
			}else if("updatePhoto".equalsIgnoreCase(operType))
			{
				String name = getPara("name");
				String img = getPara("img");
				
				Date now = new Date(); 
				/* 更新头像
				 * 相对路径:userphoto_images/2016-11-11/
				 *  */
				String path ="/userphoto_images" + "/" + this.dateFormatUtil.formatDate(now) + "/" + 
						name + "_" + System.currentTimeMillis() + ".jpg";
				/* 网络路径 */
				String websitePath = ConstatFinalUtil.BUNDLE.getString("system.websitePath") + path;
				/* 真实路径 */
				String truePath = ConstatFinalUtil.BUNDLE.getString("system.truePath") + path;
				
				/* 文件对象 */
				File souFile = new File(truePath) ; 
				/* 判断父目录是否存在,如果不存在,创建父目录 */
				if(!souFile.getParentFile().exists())
				{
					souFile.getParentFile().mkdirs();
				}
				
				BASE64Decoder decoder = new BASE64Decoder();
				FileOutputStream write = new FileOutputStream(souFile);
				byte[] decoderBytes = decoder.decodeBuffer(img);
				
				write.write(decoderBytes);
				write.close();
				
				/* 存储数据库 */
				users.setPhotoPath(websitePath);
				
				upflag = true ; 
			}
			
			/* 是否更新数据库 */
			if(upflag)
			{
				users.setUpdateTime(new Date());
				/* 保存记录 */
				resultJSON = this.usersService.updateOneUsersService(users);
			}
		} catch (Exception e)
		{
			e.printStackTrace();
			ConstatFinalUtil.LOGGER.error("查询用户详细报错了:uid:{},operType:{}", uid,operType, e);
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-1") + e.toString());
		}
		
		long ed = System.currentTimeMillis() ;
		resultJSON.put("consumeTime", (ed - st) + "毫秒");
		/* 返回结果 */
		renderJson(resultJSON);
		System.out.println(resultJSON);
	}
	
	/**
	 * 查看用户的详细信息
	 */
	public void usersWithdrawList()
	{
		ConstatFinalUtil.LOGGER.info("======usersWithdrawList======");
		long st = System.currentTimeMillis() ; 
		/* 存储结果的JSON */
		JSONObject resultJSON = new JSONObject();
		/* 接收参数 */
		String usersId = this.getPara("usersId");
		if (usersId == null)
		{
			usersId = "";
		}
		try
		{
			PageInfoUtil pageInfoUtil = this.proccedPageInfoUtil() ; 
			/* 查询数据库 */
			Map<String, Object> condMap = new HashMap<String, Object>();
			condMap.put("usersId", usersId);
			List<AUsersWithdraw> usersWithdrawList = this.usersService.findCondListUsersWithdrawService(pageInfoUtil, condMap);
			
			JSONArray withdrawArr = new JSONArray();
			for (Iterator iterator = usersWithdrawList.iterator(); iterator.hasNext();)
			{
				AUsersWithdraw usersWithdraw = (AUsersWithdraw) iterator.next();
				withdrawArr.add(usersWithdraw.toJSON());
			}
			JSONObject dataJSON = new JSONObject();
			dataJSON.put("withdrawList", withdrawArr);
			dataJSON.put("pageInfo", pageInfoUtil.toJSON());
			resultJSON.put("data", dataJSON);
			
			/* 存储结果 */
			resultJSON.put("code", "0");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
		} catch (Exception e)
		{
			ConstatFinalUtil.LOGGER.error("用户提交资料列表报错了:id:{}", e);
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-1") + e.toString());
		}
		long ed = System.currentTimeMillis() ;
		resultJSON.put("consumeTime", (ed - st) + "毫秒");
		/* 封装结果 */
		renderJson(resultJSON);
		System.out.println(resultJSON);
	}
	
	/**
	 * 查看用户的详细信息
	 */
	public void usersWithdrawInfo()
	{
		ConstatFinalUtil.LOGGER.info("======usersWithdrawInfo======");
		long st = System.currentTimeMillis() ; 
		/* 存储结果的JSON */
		JSONObject resultJSON = new JSONObject();
		/* 接收参数 */
		String uwid = this.getPara("uwid");
		if (uwid == null)
		{
			uwid = "";
		}
		try
		{
			/* 查询数据库 */
			Map<String, Object> condMap = new HashMap<String, Object>();
			condMap.put("id", uwid);
			condMap.put("extend", "true");
			AUsersWithdraw usersWithdraw = this.usersService.findOneUsersWithdrawService(condMap);
			/* 查询结果 */
			if (usersWithdraw != null)
			{
				JSONObject dataJSON = usersWithdraw.toJSON();
				resultJSON.put("data", dataJSON);
				resultJSON.put("code", "0");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			} else
			{
				resultJSON.put("code", "1");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("1"));
			}
		} catch (Exception e)
		{
			ConstatFinalUtil.LOGGER.error("查询用户提现信息详细报错了:uwid:{}", uwid, e);
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-1") + e.toString());
		}
		long ed = System.currentTimeMillis() ;
		resultJSON.put("consumeTime", (ed - st) + "毫秒");
		/* 封装结果 */
		renderJson(resultJSON);
		System.out.println(resultJSON);
	}
	
	/**
	 * 查看用户的详细信息
	 */
	public void usersWithdrawInsertSubmit()
	{
		ConstatFinalUtil.LOGGER.info("======usersWithdrawInsertSubmit======");
		long st = System.currentTimeMillis() ; 
		/* 存储结果的JSON */
		JSONObject resultJSON = new JSONObject();
		/* 接收参数 */
		String usersId = this.getPara("usersId");
		String withType = this.getPara("withType");
		String thirdName = this.getPara("thirdName");
		String extend1 = this.getPara("extend1");
		
		try
		{
			AUsersWithdraw usersWithdraw = new AUsersWithdraw();
			
			/* 设置参数 */
			usersWithdraw.setUsersId(Integer.valueOf(usersId));
			usersWithdraw.setWithType(Byte.valueOf(withType));
			usersWithdraw.setThirdName(thirdName);
			usersWithdraw.setExtend1(extend1);
			usersWithdraw.setCreateTime(new Date());
			usersWithdraw.setUpdateTime(new Date());
			usersWithdraw.setPubTime(new Date());
			
			resultJSON = this.usersService.saveOneUsersWithdrawService(usersWithdraw);
		} catch (Exception e)
		{
			ConstatFinalUtil.LOGGER.error("添加用户提现资料详细报错了:参数:{}", this.getParaMap(), e);
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-1") + e.toString());
		}
		long ed = System.currentTimeMillis() ;
		resultJSON.put("consumeTime", (ed - st) + "毫秒");
		/* 封装结果 */
		renderJson(resultJSON);
		System.out.println(resultJSON);
	}
	
	/**
	 * 用户提现资料更新提交
	 */
	public void usersWithdrawUpdateSubmit()
	{
		ConstatFinalUtil.LOGGER.info("======usersWithdrawUpdateSubmit======");
		long st = System.currentTimeMillis() ; 
		/* 存储结果的JSON */
		JSONObject resultJSON = new JSONObject();
		/* 接收参数 */
		String uwid = this.getPara("uwid");
		String usersId = this.getPara("usersId");
		String withType = this.getPara("withType");
		String thirdName = this.getPara("thirdName");
		String extend1 = this.getPara("extend1");
		try
		{
			Map<String, Object> condMap = new HashMap<String, Object>();
			condMap.put("id", uwid);
			AUsersWithdraw usersWithdraw = this.usersService.findOneUsersWithdrawService(condMap);
			if(usersWithdraw != null)
			{
				/* 设置参数 */
				usersWithdraw.setUsersId(Integer.valueOf(usersId));
				usersWithdraw.setWithType(Byte.valueOf(withType));
				usersWithdraw.setThirdName(thirdName);
				usersWithdraw.setExtend1(extend1);
				usersWithdraw.setUpdateTime(new Date());
				resultJSON = this.usersService.updateOneUsersWithdrawService(usersWithdraw);
			}else
			{
				resultJSON.put("code", "1");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("1"));
			}
		} catch (Exception e)
		{
			ConstatFinalUtil.LOGGER.error("更新用户提现资料详细报错了:参数:{}", this.getParaMap(), e);
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-1") + e.toString());
		}
		long ed = System.currentTimeMillis() ;
		resultJSON.put("consumeTime", (ed - st) + "毫秒");
		/* 封装结果 */
		renderJson(resultJSON);
		System.out.println(resultJSON);
	}
	
	/**
	 * 查看用户提现明细的详细信息
	 */
	public void withdrawHistoryList()
	{
		ConstatFinalUtil.LOGGER.info("======withdrawHistoryList======");
		long st = System.currentTimeMillis() ; 
		/* 存储结果的JSON */
		JSONObject resultJSON = new JSONObject();
		/* 接收参数 */
		String usersId = this.getPara("usersId");
		String withdrawId = this.getPara("withdrawId");
		if (usersId == null)
		{
			usersId = "";
		}
		if (withdrawId == null)
		{
			withdrawId = "";
		}
		try
		{
			PageInfoUtil pageInfoUtil = this.proccedPageInfoUtil() ; 
			/* 查询数据库 */
			Map<String, Object> condMap = new HashMap<String, Object>();
			condMap.put("usersId", usersId);
			condMap.put("withdrawId", withdrawId);
			List<AWithdrawHistory> withdrawHistoryList = this.usersService.findCondListWithdrawHistoryService(pageInfoUtil, condMap);
			
			JSONArray withdrawHistoryArr = new JSONArray();
			for (Iterator iterator = withdrawHistoryList.iterator(); iterator.hasNext();)
			{
				AWithdrawHistory withdrawHistory = (AWithdrawHistory) iterator.next();
				withdrawHistoryArr.add(withdrawHistory.toJSON());
			}
			JSONObject dataJSON = new JSONObject();
			dataJSON.put("withdrawHistoryList", withdrawHistoryArr);
			dataJSON.put("pageInfo", pageInfoUtil.toJSON());
			resultJSON.put("data", dataJSON);
			
			/* 存储结果 */
			resultJSON.put("code", "0");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
		} catch (Exception e)
		{
			ConstatFinalUtil.LOGGER.error("用户提交资料列表报错了:id:{}", e);
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-1") + e.toString());
		}
		long ed = System.currentTimeMillis() ;
		resultJSON.put("consumeTime", (ed - st) + "毫秒");
		/* 封装结果 */
		renderJson(resultJSON);
		System.out.println(resultJSON);
	}
	
	/**
	 * 查看用户提现明细
	 */
	public void withdrawHistoryInsertSubmit()
	{
		ConstatFinalUtil.LOGGER.info("======withdrawHistoryInsertSubmit======");
		long st = System.currentTimeMillis() ; 
		/* 存储结果的JSON */
		JSONObject resultJSON = new JSONObject();
		/* 接收参数 */
		String withdrawId = this.getPara("withdrawId");
		String money = this.getPara("money");
		try
		{
			AWithdrawHistory withdrawHistory = new AWithdrawHistory();
			
			/* 设置参数 */
			withdrawHistory.setWithdrawId(Integer.valueOf(withdrawId));
			withdrawHistory.setMoney(Double.valueOf(money));
			
			withdrawHistory.setCreateTime(new Date());
			withdrawHistory.setUpdateTime(new Date());
			resultJSON = this.usersService.saveOneWithdrawHistoryService(withdrawHistory);
		} catch (Exception e)
		{
			ConstatFinalUtil.LOGGER.error("添加用户提现明细报错了:参数:{}", this.getParaMap(), e);
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-1") + e.toString());
		}
		long ed = System.currentTimeMillis() ;
		resultJSON.put("consumeTime", (ed - st) + "毫秒");
		/* 封装结果 */
		renderJson(resultJSON);
		System.out.println(resultJSON);
	}
	
	/**
	 * 用户的积分明细
	 */
	public void integralHistoryList()
	{
		ConstatFinalUtil.LOGGER.info("======integralHistoryList======");
		long st = System.currentTimeMillis() ; 
		/* 存储结果的JSON */
		JSONObject resultJSON = new JSONObject();
		/* 接收参数 */
		String usersId = this.getPara("usersId");
		if (usersId == null)
		{
			usersId = "";
		}
		try
		{
			PageInfoUtil pageInfoUtil = this.proccedPageInfoUtil() ; 
			/* 查询数据库 */
			Map<String, Object> condMap = new HashMap<String, Object>();
			condMap.put("usersId", usersId);
			condMap.put("extend", "true");
			List<AIntegralHistory> integralHistoryList = this.integralService.findCondListIntegralHistoryService(pageInfoUtil, condMap);
			
			JSONArray integralHistoryArr = new JSONArray();
			for (Iterator iterator = integralHistoryList.iterator(); iterator.hasNext();)
			{
				AIntegralHistory integralHistory = (AIntegralHistory) iterator.next();
				integralHistoryArr.add(integralHistory.toJSON());
			}
			JSONObject dataJSON = new JSONObject();
			dataJSON.put("integralHistoryList", integralHistoryArr);
			dataJSON.put("pageInfo", pageInfoUtil.toJSON());
			resultJSON.put("data", dataJSON);
			
			/* 存储结果 */
			resultJSON.put("code", "0");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
		} catch (Exception e)
		{
			ConstatFinalUtil.LOGGER.error("用户提交资料列表报错了:id:{}", e);
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-1") + e.toString());
		}
		long ed = System.currentTimeMillis() ;
		resultJSON.put("consumeTime", (ed - st) + "毫秒");
		/* 封装结果 */
		renderJson(resultJSON);
		System.out.println(resultJSON);
	}
	
	/**
	 * 查看用户积分添加
	 */
	public void integralHistoryInsertSubmit()
	{
		ConstatFinalUtil.LOGGER.info("======integralHistoryInsertSubmit======");
		long st = System.currentTimeMillis() ; 
		/* 存储结果的JSON */
		JSONObject resultJSON = new JSONObject();
		/* 接收参数 */
		String usersId = this.getPara("usersId");
		String money = this.getPara("money");
		
		/* 系统自己添加 */
		int channelId = Integer.valueOf(ConstatFinalUtil.CONFIG_JSON.get("channelId") + "") ;
		try
		{
			AIntegralHistory integralHistory = new AIntegralHistory();
			
			/* 设置参数 */
			integralHistory.setChannelId(channelId);
			integralHistory.setUsersId(Integer.valueOf(usersId));
			integralHistory.setDevice("");
			integralHistory.setThirdSn(this.dateFormatUtil.format(new Date(), "yyyyMMddHHmmssS"));
			integralHistory.setIp(this.getRequest().getRemoteAddr());
			integralHistory.setContent("调用接口,增加积分");
			integralHistory.setStatus(AIntegralHistoryEnum.STATUS_ENABLE.getStauts());
			integralHistory.setMoney(Integer.valueOf(money));
			
			integralHistory.setCreateTime(new Date());
			integralHistory.setUpdateTime(new Date());
			resultJSON = this.integralService.saveOneIntegralHistoryService(integralHistory);
		} catch (Exception e)
		{
			ConstatFinalUtil.LOGGER.error("添加用户积分添加报错了:参数:{}", this.getParaMap(), e);
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-1") + e.toString());
		}
		long ed = System.currentTimeMillis() ;
		resultJSON.put("consumeTime", (ed - st) + "毫秒");
		/* 封装结果 */
		renderJson(resultJSON);
		System.out.println(resultJSON);
	}
}
